﻿using System;
using System.IO;
using Word = Microsoft.Office.Interop.Word;

namespace Word2Pdf_cs
{
    public class Word2PdfCs
    {
        public int saveAsPdf(String docPath,String pdfPath)
        {
            int status = 0;
            Word._Application word = new Word.Application();

            try
            {
                word.Visible = false;

                Word._Document document = word.Documents.Open(docPath, ReadOnly: false, NoEncodingDialog: true, Revert: false);

                document.ExportAsFixedFormat(pdfPath, Word.WdExportFormat.wdExportFormatPDF);

                document.Close(Word.WdSaveOptions.wdDoNotSaveChanges);

                status = 1;
            }
            catch (Exception ex)
            {
                saveMsg(pdfPath + ".err", ex.Message);
            }
            finally
            {
                word.Quit(Word.WdSaveOptions.wdDoNotSaveChanges);
            }

            return status;
        }

        private void saveMsg(String filePath, String msg)
        {
            try
            {
                FileStream fs = new FileStream(filePath, FileMode.Append);

                StreamWriter sw = new StreamWriter(fs);

                sw.Write(DateTime.Now.ToString() + "  " + msg);
                sw.WriteLine();

                sw.Flush();

                sw.Dispose();
                fs.Dispose();

                sw.Close();
                fs.Close();
            }
            catch (Exception ex)
            {
                
            }
        }
    }
}
